package com.uflower.product.service.impl;

import com.uflower.product.entity.AttrEntity;
import com.uflower.product.service.AttrService;
import com.uflower.product.vo.AttrGroupWithAttrsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uflower.common.utils.PageUtils;
import com.uflower.common.utils.Query;

import com.uflower.product.dao.AttrGroupDao;
import com.uflower.product.entity.AttrGroupEntity;
import com.uflower.product.service.AttrGroupService;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catId) {
        if(catId == 0){

            return queryPage(params);
        }else{
            String  key = (String) params.get("key");
            //构造查询条件
            QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
            //查询条件 数据库字段catId的值与前端传入的参数catID相同
            wrapper.eq("catelog_id",catId);
            //查询条件2 字段attr_group_id == key 或者attr_group_name like %key%
            if(!StringUtils.isEmpty(key)){
                wrapper.and((obj)->{
                    obj.eq("attr_group_id",key).or().like("attr_group_name",key);
                });
            }
            // 根据分页条件params 和查询条件wrapper进行查询
            IPage<AttrGroupEntity> page =  this.page(new Query<AttrGroupEntity>().getPage(params),wrapper);
            return new PageUtils(page);
        }
    }

    @Autowired
    private AttrService attrService;
    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCatelogId(Long catelogId) {
        //查询出当前分类catelogId下的所有的属性分组信息
        List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catelogId));
        // 查询所有分组关联的属性
        List<AttrGroupWithAttrsVo> collect = attrGroupEntities.stream().map(group->{
            AttrGroupWithAttrsVo attrsVo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(group,attrsVo);
            List<AttrEntity> attrs = attrService.getRelationAttr(attrsVo.getAttrGroupId());
            attrsVo.setAttrs(attrs);
            return attrsVo;
        }).collect(Collectors.toList());
        return collect;
    }
}